import requests
import json
from typing import Dict, Optional, Any
from utils.logger import logger
from utils.config_loader import config


class HttpClient:
    """HTTP请求封装类"""

    def __init__(self):
        self.session = requests.Session()
        self.timeout = config.get('timeout', 30)

    def get(self, url: str, params: Optional[Dict] = None, headers: Optional[Dict] = None) -> Dict[str, Any]:
        """GET请求"""
        try:
            response = self.session.get(
                url,
                params=params,
                headers=headers,
                timeout=self.timeout
            )
            return self._handle_response(response)
        except Exception as e:
            logger.error(f"GET请求失败: {url}, 错误: {str(e)}")
            raise

    def post(self, url: str, data: Optional[Dict] = None, headers: Optional[Dict] = None) -> Dict[str, Any]:
        """POST请求"""
        try:
            response = self.session.post(
                url,
                json=data,
                headers=headers,
                timeout=self.timeout
            )
            return self._handle_response(response)
        except Exception as e:
            logger.error(f"POST请求失败: {url}, 错误: {str(e)}")
            raise

    def _handle_response(self, response: requests.Response) -> Dict[str, Any]:
        """处理响应"""
        if response.status_code != 200:
            logger.warning(f"响应状态码非200: {response.status_code}")

        try:
            return response.json()
        except json.JSONDecodeError:
            logger.error("响应内容不是有效的JSON格式")
            return {"success": False, "message": "Invalid JSON response"}